package com.py.credit.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.py.credit.dao.XydUploadDao;
import com.py.credit.entity.Enterprises;
import com.py.credit.entity.FinancingRequirements;
import com.py.credit.entity.AreaFinancingStatistics;
import com.py.credit.entity.InstitutionFinancingStatistics;
import com.py.credit.entity.PlatformFinancingStatistics;
import com.py.credit.entity.Policies;
import com.py.credit.entity.FinancialInstitutions;
import com.py.credit.entity.FinancialProducts;
import com.py.credit.entity.CreditServiceAgencies;
import com.py.credit.service.XydUploadService;
import com.py.credit.utils.GMUtil;

import org.apache.commons.lang3.CharEncoding;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyrCredit.XyrDataInterfaceService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.PublicKey;
import java.util.List;

@Service
public class XydUploadServiceImpl implements XydUploadService {
    @Autowired
    private XydUploadDao xydUploadDao;

    @Override
    public String setEnterprises( String apiKey, String privateKey, String wsaddr,int type) throws Exception {
        BigInteger d = new BigInteger(privateKey, 16);
        BCECPrivateKey bcecPrivateKey = GMUtil.getPrivatekeyFromD(d);
        String subjectInfo = "";
        XyrDataInterfaceService service =    createService(wsaddr);
        String base64 = "MIIClzCCAj2gAwIBAgIBATAKBggqgRzPVQGDdTBVMQ0wCwYDVQQKEwR4eWhuMQ4wDAYDVQQIEwVo\n" +
                "ZW5hbjELMAkGA1UEBhMCQ04xDTALBgNVBAsTBHh4engxGDAWBgNVBAMTD3d3dy54eWhuLmdvdi5j\n" +
                "bjAeFw0yMTExMDUwNzM2MTRaFw0yOTEyMzExNjAwMDBaMCMxEjAQBgNVBAsMCea/rumYs+W4gjEN\n" +
                "MAsGA1UEAxMEMzE0MTCCATMwgewGByqGSM49AgEwgeACAQEwLAYHKoZIzj0BAQIhAP////7/////\n" +
                "////////////////AAAAAP//////////MEQEIP////7/////////////////////AAAAAP//////\n" +
                "///8BCAo6fqenZ9eNE1ankvPZQmn85eJ9RWrj5LdvL1BTZQOkwRBBDLEriwfGYEZX5kERmo5yZSP\n" +
                "4wu/8mYL4XFaRYkzTHTHvDc2ovT2d5xZvc7ja2khU9Cph3zGKkdAAt8y5SE58KACIQD////+////\n" +
                "////////////cgPfayHGBStTu/QJOdVBIwIBAQNCAAQMvre54B3S6hWclOejWmnJ0IJ7JYsxwyL5\n" +
                "+lruPcSrO6Eo+PSB0mswOwQVxjoDotzIFI68FAXUU4J+vvYYhl8do1QwUjAOBgNVHQ8BAf8EBAMC\n" +
                "Af4wEgYDVR0lAQH/BAgwBgYEVR0lADAsBgNVHREBAf8EIjAggRFhZG1pbkB4eWhuLmdvdi5jboIL\n" +
                "eHlobi5nb3YuY24wCgYIKoEcz1UBg3UDSAAwRQIhAM3xkTLNvbZCUFUrwFdLcouXBi3mFo+bwRZ/\n" +
                "dCM/tmhSAiAj4irzBavmY4sXZr4asMUGePPl6vbtPlNWjDLGG41Ezw==";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", apiKey);

        JSONObject object = new JSONObject();
        object.put("requestData", jsonObject);
        object.put("publicKey", base64);
        subjectInfo = service.getPublicKey(object.toJSONString());
        JSONObject json = JSONObject.parseObject(subjectInfo);
        System.out.println(json);
        String key0 = json.get("key").toString();
        String data = json.get("data").toString();
        String signatureData = json.get("signatureData").toString();
        byte[] decode = Hex.decode(key0);
        byte[] signatureData1 = Hex.decode(signatureData);
        // sm2解密
        byte[] bytes1 = GMUtil.sm2Decrypt(decode, bcecPrivateKey);
        // sm4解密
        String data1 = GMUtil.sm4Decrypt(new String(bytes1), data);
        File file = base64ToFile(data1);
        PublicKey TPublicKey = GMUtil.getPublickeyFromX509File(file);
        boolean b = GMUtil.verifySm3WithSm2(data1.getBytes(), "hnsxxzx".getBytes(), signatureData1, TPublicKey);
        JSONObject jsonObject2 = new JSONObject();
        String message = "";
        if(b){
            JSONArray jsonoArray = new JSONArray();
            if(type == 1) {
                List<Enterprises> List = xydUploadDao.getEnterprisesData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setEnterprises(jsonObject2.toJSONString());
            }else  if(type == 2) {
            	   List<FinancingRequirements> List = xydUploadDao.getFinancingRequirementsData();
                   jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                   jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                   message  = service.setFinancingRequirements(jsonObject2.toJSONString());
            }else  if(type == 3) {
                List<AreaFinancingStatistics> List = xydUploadDao.getAreaFinancingStatisticsData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setAreaFinancingStatistics(jsonObject2.toJSONString());
            }else  if(type == 4) {
                List<InstitutionFinancingStatistics> List = xydUploadDao.getInstitutionFinancingStatisticsData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setInstitutionFinancingStatistics(jsonObject2.toJSONString());
            }else  if(type == 5) {
                List<PlatformFinancingStatistics> List = xydUploadDao.getPlatformFinancingStatisticsData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setPlatformFinancingStatistics(jsonObject2.toJSONString());
            }else  if(type == 6) {
                List<Policies> List = xydUploadDao.getPoliciesData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setPolicies(jsonObject2.toJSONString());
            }else  if(type == 7) {
                List<FinancialInstitutions> List = xydUploadDao.getFinancialInstitutionsData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(List));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setFinancialInstitutions(jsonObject2.toJSONString());

            }else  if(type == 8) {
                List<FinancialProducts> EnterpriseList = xydUploadDao.getFinancialProductsData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(EnterpriseList));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setFinancialProducts(jsonObject2.toJSONString());
            }else  if(type == 9) {
                List<CreditServiceAgencies> EnterpriseList = xydUploadDao.getCreditServiceAgenciesData();
                jsonoArray =   JSONArray.parseArray(JSON.toJSONString(EnterpriseList));
                jsonObject2 = createParam(jsonoArray,TPublicKey,bcecPrivateKey,base64,apiKey);
                message  = service.setCreditServiceAgencies(jsonObject2.toJSONString());
            }
            
            System.out.println(message);
            return message;
        }else {
            jsonObject2.put("success", false);
            jsonObject2.put("errorMessage", "验签失败");
            return jsonObject2.toJSONString();
        }

    }

    public JSONObject createParam(JSONArray jsonoArray,  PublicKey TPublicKey , BCECPrivateKey bcecPrivateKey, String base64 ,String apiKey) throws Exception {
        JSONObject jsonObject2 = new JSONObject();
        byte[] msg = jsonoArray.toJSONString().getBytes(CharEncoding.ISO_8859_1);
        byte[] userId = "hnsxxzx".getBytes();
        byte[] sig = GMUtil.signSm3WithSm2(msg, userId, bcecPrivateKey);
        String signature = Hex.toHexString(sig);
        // sm4加密数据集
        String key1 = "JeF8U9wHFOMfs2Y8";
        String jsonobj = GMUtil.sm4Encrypt(key1, jsonoArray.toJSONString());
        byte[] datamsg = GMUtil.sm2Encrypt(key1.getBytes(), TPublicKey);
        String s = Hex.toHexString(datamsg);
        jsonObject2.put("requestData", jsonobj); // sm4加密的数据集
        jsonObject2.put("key", s); // sm2加密的16位随机码
        jsonObject2.put("signatureData", signature); // 签名
        jsonObject2.put("publicKey", base64); // 我的公钥
        jsonObject2.put("appKey", apiKey); // 数据授权的key
        return jsonObject2;
    }




    public XyrDataInterfaceService createService(  String wsaddr) throws Exception {
        try {
            // 创建WebService客户端代理工厂
            JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
            // 判断是否抛出异常
            factory.getOutInterceptors().add(new LoggingInInterceptor());
            // 注册webservice接口
            factory.setServiceClass(XyrDataInterfaceService.class);
            // 配置webservice地址
            factory.setAddress(wsaddr);
            // 获得接口对象
            XyrDataInterfaceService service = (XyrDataInterfaceService) factory.create();
            return service;
        } catch (Exception var17) {
           return null;
        }
    }


    public static File base64ToFile(String base64) {
        if (base64 == null || "".equals(base64)) {
            return null;
        }
        byte[] buff = Base64.decode(base64);
        File file = null;
        FileOutputStream fout = null;
        try {
            file = File.createTempFile("tmp", null);
            System.out.println(file);
            fout = new FileOutputStream(file);
            fout.write(buff);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
